package com.opentool;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.dns.DatagramDnsQuery;
import io.netty.handler.codec.dns.DatagramDnsQueryEncoder;
import io.netty.handler.codec.dns.DatagramDnsResponseDecoder;

public class DnsClient {
    public Channel channel;
    public void start(String host,int port){
        Bootstrap bootstrap=new Bootstrap();
        NioEventLoopGroup workerGroup=new NioEventLoopGroup();
        bootstrap.group(workerGroup)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    protected void initChannel(NioDatagramChannel ch)throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new DatagramDnsQueryEncoder());
                        pipeline.addLast(new DatagramDnsResponseDecoder());
                        pipeline.addLast(new DnsClientHandler());
                    }
         });
        this.channel = bootstrap.connect(host,port).syncUninterruptibly().channel();
    }

    public void send(DatagramDnsQuery datagramDnsQuery){
        channel.writeAndFlush(datagramDnsQuery);
    }
}
